package com.nc.delivery_project.server.service;

import com.nc.delivery_project.server.dao.AbstractDao;
import com.nc.delivery_project.server.domain.Role;
import com.nc.delivery_project.server.dao.UserDao;
import com.nc.delivery_project.server.domain.User;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by miroshnik on 02.12.14.
 */
public class UserService extends BaseService<User> {

    public UserService() {
        this(new UserDao());
    }

    public UserService(Connection connection, boolean isAutoCloseConnection) {
        super(new UserDao(), connection, isAutoCloseConnection);
    }

    public UserService(AbstractDao<User> dao) {
        super(dao);
    }

    @Override
    public User read(int id) {
        User user = null;
        
        try {
            Connection conn = getConnection();
            dao.setConnection(conn);
            user = dao.read(id);
            
            if (user != null) {
                Role userRole = new RoleService(conn, false).read(user.getRole().getId());
                if (userRole != null) {
                    user.getRole().setTitle(userRole.getTitle());
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return user;
    }

    @Override
    public List<User> read() {
        List<User> users = null;
        
        try {
            Connection conn = getConnection();
            dao.setConnection(conn);
            users = dao.read();
            
            RoleService roleService = new RoleService(conn, false);
            
            for (User user : users) {
                user.setRole(roleService.read(user.getRole().getId()));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return users;
    }
}
